﻿using DeepEarth.Core;
using ProjNet.CoordinateSystems.Transformations;
using ProjNet.CoordinateSystems;
using System;
using System.Windows;
namespace DeepEarth.Toolkit.Controls.Measure
{
    public class AreaHelper
    {
        public static int Zone(double longitude)
        {
            return (int)Math.Ceiling((longitude + 180) / 6);
        }

        public static UTMLocation ConvertToUTM(Location location, int zone)
        {
            var ctfac = new CoordinateTransformationFactory();
            var wgs84geo = GeographicCoordinateSystem.WGS84;
            var utm = ProjectedCoordinateSystem.WGS84_UTM(zone, location.Latitude > 0);
            var trans = ctfac.CreateFromCoordinateSystems(wgs84geo, utm);
            Point pUtm = trans.MathTransform.Transform(new Point(location.Longitude, location.Latitude));

            UTMLocation utmLocation = new UTMLocation
            {
                Zone = new Zone
                {
                    Number = zone,
                    Hemisphere = LatitudeToHemisphere(location.Latitude)
                },
                Easting = Math.Round(pUtm.X, 0),
                Northing = Math.Round(pUtm.Y, 0)
            };

            return utmLocation;
        }


        public static UTMLocation ConvertToUTM(Location location)
        {
            var zone = (int)Math.Ceiling((location.Longitude + 180) / 6);
            return ConvertToUTM(location, zone);
        }


        public static Location ConvertToLatLon(UTMLocation location)
        {
            var ctfac = new CoordinateTransformationFactory();
            var wgs84geo = GeographicCoordinateSystem.WGS84;
            var zone = location.Zone.Number;
            var utm = ProjectedCoordinateSystem.WGS84_UTM(zone, location.Zone.Hemisphere == Hemisphere.North);
            var trans = ctfac.CreateFromCoordinateSystems(utm, wgs84geo);

            Point latLon = trans.MathTransform.Transform(new Point(location.Easting, location.Northing));

            return new Location
            {
                Latitude = latLon.Y,
                Longitude = latLon.X
            };
        }

        public static Hemisphere LatitudeToHemisphere(double latitude)
        {
            return latitude >= 0 ? Hemisphere.North : Hemisphere.South;
        }

        public static double ZoneEasternLongitude(int zoneNumber)
        {
            return (zoneNumber * 6) - 180;
        }

        public static double ZoneWesternLongitude(int zoneNumber)
        {
            return ZoneEasternLongitude(zoneNumber) - 6;
        }
    }
}
